package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @RequiredPermission(name = "部门列表", expression = "department:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageResult<Department> pageResult = departmentService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "department/list";
    }

    @RequiredPermission(name = "部门删除", expression = "department:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JSONResult delete(Long id) {

        try {

            if (id != null) {
                departmentService.delete(id);
            }
            return new JSONResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONResult(false, "删除失败");
        }
    }


    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) {
            Department department = departmentService.get(id);
            model.addAttribute("department", department);
        }
        return "department/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Department department) {

        if (department.getId() != null) {
            departmentService.update(department);

        } else {
            departmentService.save(department);
        }
        return "redirect:/department/list.do";
    }


}
